package com.example.demo.netty.multi;

import com.example.demo.netty.CustomChannelInBoundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

// 假设有两个线程，一个用于监听连接，一个用于处理连接后的操作
class MultiThreadReactor {
    public static void main (String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // Boss线程组，通常只需要一个线程
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // Worker线程组，线程数量可以根据需要配置
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel (SocketChannel ch) throws Exception {
                            // 设置ChannelPipeline中的处理器
                            ch.pipeline().addLast(new StringDecoder());
//                            ch.pipeline().addLast(new CustomChannelInBoundHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置用于临时存放已完成三次握手连接的队列长度
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // 设置保持长连接

            // 绑定端口并启动服务器
            ChannelFuture f = b.bind(9090).sync();
            // 等待服务器关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅关闭EventLoopGroup
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}